import {Button,Modal,Watermark,Divider} from 'antd';
import {PrinterOutlined} from '@ant-design/icons';
import Loading from '@/components/Loading/index.tsx';

import styles from './Detail.module.scss';
import './Detail.global.scss';
import { useState } from 'react';
import { useEffect } from 'react';
import { req } from '@/common/methods';
import pub from '@/units/pub';

let timer = undefined;

const Detail = (props) => {
    const time = new Date(props.item.time);
    const [reqCount,setReqCount] = useState(0);
    const [loading,setLoading] = useState(true);
    const [data,setData] = useState([]);
    const [goods,setGoods] = useState({});
    const [timeStr,setTimeStr] = useState('');
    const changeTime = () => {
        clearInterval(timer);
        const handleTimeStr = ()=>{
            if(!document.querySelector('#prePrintForTimeHide')){
                clearInterval(timer);
                return;
            }
            const date = new Date();
            setTimeStr(`${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()} ${date.getHours()}:${(''+date.getMinutes()).padStart(2,'0')}:${(''+date.getSeconds()).padStart(2,'0')}`);
        };
        handleTimeStr();
        //timer = setInterval(handleTimeStr,1000);
    }
    useEffect(()=>{
        changeTime();
    },[]);
    const fetchData = () => {
        setLoading(true);
        req('/api/goods/easy_get').then(data => {
            setGoods(data);
            return req('/api/storage/detail_by_doc',{doc_id:props.item.doc_id});
        }).then(data => {
            setData(data);
            setLoading(false);
        }).catch(error => {
            Modal.error({
                title:'错误',
                content:<>无法生成单据详情,{''+error}</>
            })
        });
    }
    useEffect(()=>{
        fetchData();
    },[reqCount])
    return <>
        {/* 这是详情组件{JSON.stringify(props)} */}
        <div id="prePrintForTimeHide"></div>
        {loading?<Loading/>:<div>
            <div style={{display:'flex',justifyContent:'flex-end'}}>
                <Button onClick={()=>{
                    const targetElement = document.querySelector('div#prePrint');
                    document.body.childNodes.forEach(item => {
                        if(item && item.tagName){
                            if(item.tagName === 'DIV'){
                                item.style.display = 'none';
                            }
                        }
                    });
                    document.body.appendChild(targetElement);
                    window.print();
                    document.body.removeChild(targetElement);
                    //const targetParentElement = document.querySelector('div#prePrintParent');
                    //targetParentElement.appendChild(targetElement);
                    document.body.childNodes.forEach(item => {
                        if(item && item.tagName){
                            if(item.tagName === 'DIV'){
                                item.style.display = 'block';
                            }
                        }
                    });
                    setReqCount(reqCount+1);
                }} icon={<PrinterOutlined />}>打印单据</Button>
            </div>
            <div id="prePrintParent">
                <div id="prePrint" data-history-detail-pre-print>
                    <Watermark content="麟泽康养综合行政部">
                        <div className="pp-title-area">
                            {/* <h1>{props.item.isIn?'入':'出'}库单</h1> */}
                            <h1>{props.item.method === 30 ? '盘点单' :(props.item.isIn?(props.item.method === 10 ? '进货' : '收回')+'入库单':(props.item.method === 10 ? '退货' :'领用')+'出库单')}</h1>
                            <div className='pp-title-area-no'>
                                <span className='no-this'>NO:</span>
                                <span className='no-wri'>{props.item.doc_id}</span>
                            </div>
                        </div>
                        <div className='pp-subtitle-area'>
                            <div>{props.item.method === 10 ? `供货商` :`部门`}：{props.item.method === 30 ? '' :((props.item.method === 10 ? props.suppliers[props.item.depart] : props.depart[props.item.depart]) || <>
                                <font color="red">未知[{props.item.depart}]</font>
                            </>)}</div>
                            <div>
                                <span className="pp-subtitle-time-wri">{time.getFullYear()}</span>
                                <span className="pp-subtitle-time-pri">年</span>
                                <span className="pp-subtitle-time-wri">{time.getMonth()+1}</span>
                                <span className="pp-subtitle-time-pri">月</span>
                                <span className="pp-subtitle-time-wri">{time.getDate()}</span>
                                <span className="pp-subtitle-time-pri">日</span>
                            </div>
                        </div>
                        <table className="pp-table">
                            <thead>
                                <tr>
                                    <th>序号</th>
                                    <th>产品名称</th>
                                    <th>规格</th>
                                    <th>单位</th>
                                    {props.item.method === 30 ? (<>
                                        <th>账存</th>
                                        <th>实存</th>
                                        <th>变动</th>                                
                                    </>) : (<>
                                        <th>{props.item.isIn?'入':'出'}库数量</th>
                                        <th>结余</th>
                                    </>) }

                                    <th>备注</th>
                                </tr>
                            </thead>
                            <tbody>
                                {data.map((item,index) => <tr key={item.id}>
                                    <td className="cent">{index+1}</td>
                                    <td className="cent">{goods[item.goods_id]?.name || <>
                                        <font color="red">已删除产品[{item.goods_id}]</font>
                                    </>}</td>
                                    <td className="cent">{goods[item.goods_id]?.specs || '-'}</td>
                                    <td className="cent">{goods[item.goods_id]?.unit || '-'}</td>
                                    {props.item.method === 30 ? <>
                                        <td className="cent">{item.before_count}</td>
                                        <td className="cent">{item.after_count}</td>
                                        <td className="cent">{item.change_count}</td>
                                    </> : <>
                                        <td className="cent">{Math.abs(item.change_count)}</td>
                                        <td className="cent">{item.after_count}</td>
                                    </> }
                                    <td>{item.remark}</td>
                                </tr>)}                                
                            </tbody>
                        </table>
                        <div className="pp-bottom-area">
                            <span data-user-id={props.item.user_id}>仓管：{(pub.getData('all_user') || []).find(item0 => item0?.id === props.item.user_id)?.username || ''}</span>
                            <span>{props.item.method === 10 ? (props.item.isIn?'进货人':'退货人') : (props.item.method === 20 ? (props.item.isIn?'申请人':'申请人') : '盘点人')}：{props.item.requ}</span>
                            <span>{props.item.method === 10 ? (props.item.isIn?'确认人':'确认人') : (props.item.method === 20 ? (props.item.isIn?'收回人':'领用人') : '确认人')}：{props.item.empl}</span>
                        </div>
                    </Watermark>
                    <Divider orientation="left">
                        <span id="prePrintForTime" style={{fontSize:'12px',opacity:0.5}}>打印时间:{timeStr}</span>
                    </Divider>
                </div>
            </div>

        </div>}
    </>
}
export default Detail;